<template>
    <!-- 个人资料区域开始 -->
    <div class="card" style="margin-top: 40px">
        <el-descriptions title="个人资料" direction="vertical" border style="margin: 10px 40px 0 40px;" :data="data.profile">
            <el-descriptions-item :rowspan="2" :width="140" label="头像" align="center">
                <div class="avatar-container">
                    <el-upload
                        class="avatar-uploader"
                        :action="`http://localhost:8000/api/${data.profile.user_id}/upload-profile-photo`"
                        :show-file-list="false"
                        :on-success="handleUploadSuccess"
                        :before-upload="beforeUpload"
                    >  <!-- action:请求路径 单大括号插值 + v-bind（：的全称）动态绑定属性-->
                        <div class="avatar-wrapper" @mouseenter="showReplaceTip = true" @mouseleave="showReplaceTip = false">
                            <el-avatar :src="data.profile.profile_photo_path" :size="100" fit="cover" shape="circle" @error="errorHandler">
                                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载错误"/> <!--图片加载失败的回退行为-->
                            </el-avatar>
                            <div v-if="showReplaceTip" class="replace-tip">点击上传</div>
                        </div>
                    </el-upload>
                </div>
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称" prop="username">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.username }}</span>
                    <el-input v-else v-model="data.profile.username" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="电话" prop="phone">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.phone }}</span>
                    <el-input v-else v-model="data.profile.phone" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="电子邮件" prop="email">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.email }}</span>
                    <el-input v-else v-model="data.profile.email" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="角色信息">
                <template #default>
                    <span>角色名：</span>
                    <span  style="margin-right: 20px">{{ data.profile.role.roleName }}</span>
                    <span>角色描述：</span>
                    <span>{{ data.profile.role.description }}</span>
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :width="180">
                <template #default>
                    <span>{{ data.profile.created_at }}</span>
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="最近更新时间" style="right: 0">
                <template #default>
                    <span>{{ data.profile.updated_at }}</span>
                </template>
            </el-descriptions-item>
        </el-descriptions>
        <div style="display: flex; align-items: center; justify-content: center; margin-top: 10px">
            <el-button v-if="!data.isEditing" @click="data.isEditing = !data.isEditing" type="primary" style="width: 100px">
                编辑资料
            </el-button>
            <el-button v-else @click="updateProfile" type="primary" style="width: 100px">
                保存信息
            </el-button>
        </div>
    </div>
    <!-- 个人资料区域结束 -->

    <!--修改密码 + 账号注销区域开始-->
    <div class="card">
        <div v-if="data.editView" style="display: flex; align-items: center">
            <el-form ref="passwordRef" :model="data.password" :rules="data.rules" label-width="80px" style="display: flex; align-items: center; margin: 10px 20px 0">
                <el-form-item label="新密码" prop="newPassword">
                    <el-input  v-model="data.password.newPassword" show-password  style="width: 200px" placeholder="请输入新密码"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="data.password.confirmPassword" show-password  style="width: 200px" placeholder="确认新密码"/>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="submitForm" style="width: 100px">确定</el-button>
            <el-button @click="data.editView = false" style="width: 100px">取消</el-button>
        </div>
        <div v-else>
            <span style="margin-left: 40px">密码：</span>
            <el-button type="primary" link style="margin-left: 80%" @click="openEditView">修改密码</el-button>
        </div>
    </div>
    <!--修改密码区域结束-->
</template>

<script setup>
import { reactive, ref, computed} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

const showReplaceTip = ref(false); // 鼠标悬停上传字段展示控制
const errorHandler = () => true //图片加载失败的回退行为

let user;
//获取本地存储中的用户信息
let loginUser = localStorage.getItem('admin_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}

const data = reactive({
    isEditing: false,
    editView: false,
    password: {
        newPassword: '',
        confirmPassword: ''
    },
    profile: {
        profile_photo_path: user?.profile_photo_path || '',
        user_id: user?.user_id || '',
        username: user?.username || '',
        password: user?.password || '',
        phone: user?.phone || '',
        email: user?.email || '',
        role_id: user?.role_id || undefined,
        created_at: user?.created_at || undefined,
        updated_at: user?.updated_at || undefined,
        role: {
            role_id: user?.role_id || undefined,
            roleName: user?.role.roleName || '',
            description: user?.role.description || '',
        },
    },
    rules: {
        newPassword: [
            { required: true, message: '请输入最新密码', trigger: 'blur' },
            {min: 6, message: '最少输入6位', trigger: 'blur'},
        ],
        confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            {min: 6, message: '最少输入6位', trigger: 'blur'},
        ],
    },
})

const handleUploadSuccess = (response) => {
    data.profile.updated_at = currentTime;
    if (response.code === "200") {
        data.profile.profile_photo_path = response.data.profile_photo_path;// 更新 data.profile.profile_photo_path
        localStorage.setItem('admin_user', JSON.stringify(data.profile));// 更新本地存储图片
        ElMessage.success("上传成功")
        location.reload(); // 刷新页面
    } else {
        ElMessage.error(response.msg)
    }
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';  // 更通用的图片类型校验
    const isLt2M = file.size / 1024 / 1024 < 2;  // 限制文件大小不超过2MB
    if (!isJpgOrPng) {
        ElMessage.error('只能上传图片文件（JPEG/PNG/JPG等）');
    }
    if (!isLt2M) {
        ElMessage.error('文件大小不能超过2MB');
    }
    return isJpgOrPng && isLt2M;
};


//保存数据到后端的逻辑
const updateProfile = () => {
    data.profile.updated_at = currentTime;
    request.post('/api/updateprofile', data.profile,).then(res => {
        if (res.code === '200') {
            ElMessage.success('保存成功')
            localStorage.setItem('admin_user', JSON.stringify(data.profile));// 更新本地存储数据
            location.reload(); // 刷新页面
        } else {
            ElMessage.error('保存失败')
        }
    })
    data.isEditing = false;
};



const passwordRef = ref();
const openEditView =  () => {
    data.editView = true;
}
// 表单验证和提交数据到后端的逻辑
const submitForm = () => {
    passwordRef.value.validate((valid) => {  // 触发表单验证
        if (valid) {
            if (data.password.newPassword === data.password.confirmPassword) {
                request.post('/api/updatepassword' ,data.password.newPassword,{
                    params: { user_id: data.profile.user_id }
                }).then(res => {
                    if (res.code === '200') {
                        ElMessage.success("密码更新成功")
                        data.profile.password = data.password.newPassword; // 更新profile数据
                        data.profile.updated_at = currentTime;
                        localStorage.setItem('admin_user', JSON.stringify(data.profile));// 更新本地存储数据
                        location.reload(); // 刷新页面
                        data.editView = false;
                    } else {
                        ElMessage.error('密码更新失败');
                    }
                }).catch((error) => {
                    ElMessage.error('请求出错：' + error.message);
                });
            } else {
                ElMessage.error("两次密码不一致, 请确认密码")
            }
        }
    })
};


//当前时间处理
const currentTime = ref(''); // 使用 ref 定义一个响应式变量来存储当前时间
const updateTime = () => {  // 在组件挂载时获取当前时间并格式化
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 调用函数获取并设置初始时间
updateTime();
</script>


<style>
.avatar-uploader {
    display: block;
}

 .avatar-uploader .el-upload {
     border: 1px dashed var(--el-border-color);
     cursor: pointer;
     position: relative;
     overflow: hidden;
     transition: var(--el-transition-duration-fast);
     border-radius: 50%;
 }

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}


.avatar-container {
    position: relative;
}

.avatar-wrapper {
    position: relative;
    width: 100px; /* 可根据需要调整头像大小 */
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.replace-tip {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.avatar-wrapper:hover .replace-tip {
    opacity: 1;
}
</style>